package com.zhongxiangspace.tools;

import com.zhongxiangspace.entity.FreemarkerHtmlConfiguration;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;


/**
 * freemarker 生成静态html
 */
public class FreeMarkerViewUtil extends FreeMarkerView {

    private static final String Path = FreeMarkerViewUtil.class.getResource("/").toString() + "templates/";

    public static void createHtml(FreemarkerHtmlConfiguration freemarkerHtmlConfiguration) {
        Writer out = null;
        boolean fag=true;
        try { //创建freemarker核心配置对象,指定freemarker版本
            Configuration configuration = new Configuration(Configuration.getVersion());
            //设置默认编码 Object
            configuration.setDefaultEncoding("UTF-8");
            //指定服务器模板文件所在路径
            configuration.setDirectoryForTemplateLoading(new File(FreeMarkerViewUtil.Path.substring(6, FreeMarkerViewUtil.Path.length())+"html/pc"));
            //从模板文件路径下面获取模板文件对象
            Template template = configuration.getTemplate(freemarkerHtmlConfiguration.getTemplateName());
            //创建一个输出对象,把数据输出daoHtml页面
            out = new FileWriter(new File(freemarkerHtmlConfiguration.getHtmlPath()));
            //生成Html页面
            template.process(freemarkerHtmlConfiguration.getData(), out);
        } catch (Exception e) {
            fag=false;
            e.printStackTrace();
        } finally {
            try { //关闭资源
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(!fag){
                File file =new File(freemarkerHtmlConfiguration.getHtmlPath());
                if(file.exists()){
                    file.delete();
                }
            }
        }
    }
}
